package demo02;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @author: WangPeng
 * @createTime: 2022/11/03 19:39
 * @description:
 * @version: v1.0
 */
public class Test03 {
    public static void main(String[] args) {
        List<People> list = new ArrayList<>();
        list.add(new People("AA",20));
        list.add(new People("BB",19));
        list.add(new People("CC",18));
        list.add(new People("DD",17));
        //方式一:
        Comparator<People> comparator1 = new Comparator<People>(){
            @Override
            public int compare(People o1, People o2) {
                return o1.getAge()-o2.getAge();
            }
        };
        Collections.sort(list,comparator1);
        System.out.println(list);
        //方式二:
        //如果执行语句只有一句，且无返回值，{}可以省略；
        //若有返回值，则若想省去{}，则必须同时省略return，且执行语句也保证只有一句
        Comparator<People> comparator2=(o1,o2)->o1.getAge()-o2.getAge();
        //Comparator<People> comparator2=(o1,o2)->{ return o1.getAge()-o2.getAge(); };

        Collections.sort(list,comparator2);

        //可以直接传递方法体
        Collections.sort(list,(o1,o2)->o1.getAge()-o2.getAge());

        System.out.println(list);

    }
}

class People {
    private String name;
    private Integer age;

    public People() {
    }

    public People(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "People{" +
                "name='" + name + '\'' +
                ", age='" + age + '\'' +
                '}';
    }
}